import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class HttpService {

  private httpurl = 'http://115.159.5.34:8080/YYGHHospital/api/';

  constructor(private http: Http) { }
  //get方法
  httpGet(apiName: string, params: any): Observable<any> {
    return this.http.get(this.httpurl + apiName, { search: params })
      .map(this.extractData)
      .catch(this.handleError);
  }
  //post方法
  httpPost(apiName: string, params: any): Observable<any> {
    return this.http.post(this.httpurl + apiName, { search: params })
      .map(this.extractData)
      .catch(this.handleError);
  }
  //返回数据
  private extractData(res: Response) {
    if (res.status < 200 || res.status >= 300) {
      throw new Error('Bad response status: ' + res.status);
    }
    let body = res.json();
    //console.log(res);
    return body.data || {};
  }
  //返回失败
  private handleError(error: any) {
    let errMsg = error.message || 'Server error';
    console.error(errMsg);
    return Observable.throw(errMsg);
  }
}
